package com.manteam.iwant2learn.questions.client.ui;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;

import com.manteam.framework.exceptions.SystemException;
import com.manteam.iwant2learn.questions.client.handler.MaintainQuestionsHandler;
import com.manteam.iwant2learn.questions.exceptions.MaintainQuestionsException;
import com.manteam.iwant2learn.training.client.handler.TrainingUIHandler;
import com.manteam.iwant2learn.vo.ExamQuestionsVO;

public class QuestionDetailsInterfaceUI extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4461834302352455051L;

	private JLabel answerImageLabel;
	private JLabel answerLabel;
	private JPanel answerPanel;
	private JScrollPane answerScrollPane;
	private JTextArea answerTextArea;
	private JPanel buttonPanel;
	private JButton choosePathButton;
	private JButton chooseQuestionImageButton;
	private JButton closeButton;
	private JTextField answerImagePathTextField;
	private JMenu jMenu1;
	private JMenu jMenu2;
	private JMenuBar mainMenuBar;
	private JPanel mainPanel;
	private JLabel moduleNameLabel;
	private JTextField moduleNameTextField;
	private JLabel questionImageLabel;
	private JTextField questionImagePathTextField;
	private JLabel questionLabel;
	private JPanel questionPanel;
	private JScrollPane questionScrollPane;
	private JTextArea questionTextArea;
	private JLabel questionYearLabel;
	private JTextField questionYearTextField;
	private JButton saveButton;
	private JPanel statusPanel;
	private JLabel subjectNameLabel;
	private JTextField subjectNameTextField;
	private JPanel subjectPanel;
	private JLabel submoduleNameLabel;
	private JTextField submoduleNameTextField;

	/** Creates new form QuestionInterfaceUI */
	public QuestionDetailsInterfaceUI() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {
		GridBagConstraints gridBagConstraints;

		mainPanel = new JPanel();
		questionPanel = new JPanel();
		questionLabel = new JLabel();
		questionScrollPane = new JScrollPane();
		questionTextArea = new JTextArea();
		questionImageLabel = new JLabel();
		questionImagePathTextField = new JTextField();
		chooseQuestionImageButton = new JButton();
		questionYearLabel = new JLabel();
		questionYearTextField = new JTextField();
		answerPanel = new JPanel();
		answerLabel = new JLabel();
		answerImageLabel = new JLabel();
		answerScrollPane = new JScrollPane();
		answerTextArea = new JTextArea();
		answerImagePathTextField = new JTextField();
		choosePathButton = new JButton();
		subjectPanel = new JPanel();
		subjectNameLabel = new JLabel();
		subjectNameTextField = new JTextField();
		moduleNameLabel = new JLabel();
		moduleNameTextField = new JTextField();
		submoduleNameLabel = new JLabel();
		submoduleNameTextField = new JTextField();
		buttonPanel = new JPanel();
		closeButton = new JButton();
		saveButton = new JButton();
		statusPanel = new JPanel();
		mainMenuBar = new JMenuBar();
		jMenu1 = new JMenu();
		jMenu2 = new JMenu();

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		mainPanel.setLayout(new GridBagLayout());

		questionPanel.setBorder(BorderFactory
				.createTitledBorder("Question Details"));
		questionPanel.setLayout(new GridBagLayout());

		questionLabel.setText("Question");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.anchor = GridBagConstraints.NORTHEAST;
		questionPanel.add(questionLabel, gridBagConstraints);

		questionTextArea.setColumns(20);
		questionTextArea.setRows(5);
		questionScrollPane.setViewportView(questionTextArea);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridwidth = 2;
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(5, 5, 5, 5);
		questionPanel.add(questionScrollPane, gridBagConstraints);

		questionImageLabel.setText("Question Image");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.insets = new Insets(5, 10, 5, 5);
		questionPanel.add(questionImageLabel, gridBagConstraints);
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(5, 5, 5, 5);
		questionPanel.add(questionImagePathTextField, gridBagConstraints);

		chooseQuestionImageButton.setText("Browse");
		chooseQuestionImageButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				chooseQuestionImageButtonActionPerformed(evt);
			}
		});
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.insets = new Insets(5, 5, 5, 10);
		questionPanel.add(chooseQuestionImageButton, gridBagConstraints);

		questionYearLabel.setText("Qn Year Mark");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 2;
		gridBagConstraints.insets = new Insets(5, 10, 10, 5);
		questionPanel.add(questionYearLabel, gridBagConstraints);
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 2;
		gridBagConstraints.gridwidth = 2;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(5, 5, 10, 10);
		questionPanel.add(questionYearTextField, gridBagConstraints);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		mainPanel.add(questionPanel, gridBagConstraints);

		answerPanel.setBorder(BorderFactory
				.createTitledBorder("Answer Details"));
		answerPanel.setLayout(new GridBagLayout());

		answerLabel.setText("Answer");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.anchor = GridBagConstraints.NORTHEAST;
		gridBagConstraints.insets = new Insets(10, 10, 5, 5);
		answerPanel.add(answerLabel, gridBagConstraints);

		answerImageLabel.setText("Answer Image");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.insets = new Insets(5, 10, 10, 5);
		answerPanel.add(answerImageLabel, gridBagConstraints);

		answerTextArea.setColumns(20);
		answerTextArea.setRows(5);
		answerScrollPane.setViewportView(answerTextArea);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridwidth = 2;
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.insets = new Insets(5, 5, 5, 5);
		answerPanel.add(answerScrollPane, gridBagConstraints);
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(5, 5, 10, 5);
		answerPanel.add(answerImagePathTextField, gridBagConstraints);

		choosePathButton.setText("Browse");
		choosePathButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				choosePathButtonActionPerformed(evt);
			}
		});
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.insets = new Insets(5, 5, 10, 10);
		answerPanel.add(choosePathButton, gridBagConstraints);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 2;
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.anchor = GridBagConstraints.SOUTH;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		mainPanel.add(answerPanel, gridBagConstraints);

		subjectPanel.setBorder(BorderFactory
				.createTitledBorder("Subject Details"));
		subjectPanel.setLayout(new GridBagLayout());

		subjectNameLabel.setText("Subject Name");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.insets = new Insets(10, 10, 5, 5);
		subjectPanel.add(subjectNameLabel, gridBagConstraints);

		subjectNameTextField.setMinimumSize(new Dimension(19, 22));
		subjectNameTextField.setPreferredSize(new Dimension(200, 22));
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.anchor = GridBagConstraints.WEST;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(5, 5, 5, 5);
		subjectPanel.add(subjectNameTextField, gridBagConstraints);

		moduleNameLabel.setText("Module Name");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.insets = new Insets(5, 10, 10, 5);
		subjectPanel.add(moduleNameLabel, gridBagConstraints);

		moduleNameTextField.setPreferredSize(new Dimension(200, 22));
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.anchor = GridBagConstraints.WEST;
		gridBagConstraints.insets = new Insets(5, 5, 10, 5);
		subjectPanel.add(moduleNameTextField, gridBagConstraints);

		submoduleNameLabel.setText("Submodule Name");
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.anchor = GridBagConstraints.EAST;
		gridBagConstraints.insets = new Insets(5, 0, 10, 5);
		subjectPanel.add(submoduleNameLabel, gridBagConstraints);

		submoduleNameTextField.setPreferredSize(new Dimension(200, 22));
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 3;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.anchor = GridBagConstraints.EAST;
		gridBagConstraints.insets = new Insets(5, 5, 10, 10);
		subjectPanel.add(submoduleNameTextField, gridBagConstraints);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		mainPanel.add(subjectPanel, gridBagConstraints);

		buttonPanel.setLayout(new GridBagLayout());

		closeButton.setText("Close");
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				closeButtonActionPerformed(evt);
			}
		});
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.anchor = GridBagConstraints.EAST;
		gridBagConstraints.insets = new Insets(10, 5, 10, 10);
		buttonPanel.add(closeButton, gridBagConstraints);

		saveButton.setText("Save");
		saveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				saveButtonActionPerformed(evt);
			}
		});
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.anchor = GridBagConstraints.EAST;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(10, 0, 10, 5);
		buttonPanel.add(saveButton, gridBagConstraints);

		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 3;
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.anchor = GridBagConstraints.SOUTH;
		gridBagConstraints.weightx = 1.0;
		mainPanel.add(buttonPanel, gridBagConstraints);

		statusPanel.setBorder(BorderFactory.createEtchedBorder());

		GroupLayout statusPanelLayout = new GroupLayout(statusPanel);
		statusPanel.setLayout(statusPanelLayout);
		statusPanelLayout.setHorizontalGroup(statusPanelLayout
				.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0,
						855, Short.MAX_VALUE));
		statusPanelLayout.setVerticalGroup(statusPanelLayout
				.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0,
						17, Short.MAX_VALUE));

		jMenu1.setText("File");
		mainMenuBar.add(jMenu1);

		jMenu2.setText("Edit");
		mainMenuBar.add(jMenu2);

		setJMenuBar(mainMenuBar);

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addComponent(mainPanel, GroupLayout.Alignment.TRAILING,
						GroupLayout.PREFERRED_SIZE, 859, Short.MAX_VALUE)
				.addGroup(
						layout.createParallelGroup(
								GroupLayout.Alignment.LEADING).addComponent(
								statusPanel, GroupLayout.DEFAULT_SIZE,
								GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addComponent(mainPanel,
										GroupLayout.DEFAULT_SIZE, 583,
										Short.MAX_VALUE)
								.addContainerGap(21, Short.MAX_VALUE))
				.addGroup(
						layout.createParallelGroup(
								GroupLayout.Alignment.LEADING).addGroup(
								layout.createSequentialGroup()
										.addContainerGap(583, Short.MAX_VALUE)
										.addComponent(statusPanel,
												GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE))));

		pack();
	}// </editor-fold>

	private void chooseQuestionImageButtonActionPerformed(ActionEvent evt) {
		JFileChooser chooser = new JFileChooser();
	    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
	    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
	    /*ExampleFileFilter filter = new ExampleFileFilter();
	    filter.addExtension("jpg");
	    filter.addExtension("gif");
	    filter.setDescription("JPG & GIF Images");
	    chooser.setFileFilter(filter);*/
		//chooser.setFileFilter(filter)
	    int returnVal = chooser.showOpenDialog(this);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	       System.out.println("You chose to open this file: " +
	            chooser.getSelectedFile().getName());
	       questionImagePathTextField.setText(chooser.getSelectedFile().getAbsolutePath());
	    }
	}

	private void choosePathButtonActionPerformed(ActionEvent evt) {
		JFileChooser chooser = new JFileChooser();
	    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
	    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
	    /*ExampleFileFilter filter = new ExampleFileFilter();
	    filter.addExtension("jpg");
	    filter.addExtension("gif");
	    filter.setDescription("JPG & GIF Images");
	    chooser.setFileFilter(filter);*/
	    int returnVal = chooser.showOpenDialog(this);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	       System.out.println("You chose to open this file: " +
	            chooser.getSelectedFile().getName());
	       answerImagePathTextField.setText(chooser.getSelectedFile().getAbsolutePath());
	    }
	}

	private void saveButtonActionPerformed(ActionEvent evt) {
		ExamQuestionsVO examQuestionsVO = null;
		if (isValidForSave()) {
			examQuestionsVO = generateExamQuestionsVO();
			try {
				if (MaintainQuestionsHandler.getInstance().saveQuestion(examQuestionsVO)) {
					JOptionPane.showMessageDialog(this,
							"Question saved Succesfully", "Info",
							JOptionPane.INFORMATION_MESSAGE);
					dispose();
				} else {
					JOptionPane.showMessageDialog(this,
							"Record Not saved", "Inane error",
							JOptionPane.ERROR_MESSAGE);
					saveButton.requestFocus();
				}
			} catch (SystemException systemException) {
				JOptionPane.showMessageDialog(this,
						systemException.getMessage(), "Inane error",
						JOptionPane.ERROR_MESSAGE);
				saveButton.requestFocus();
				systemException.printStackTrace();
			} catch (MaintainQuestionsException maintainQuestionsException) {
				JOptionPane.showMessageDialog(this,
						maintainQuestionsException.getMessage(), "Inane error",
						JOptionPane.ERROR_MESSAGE);
				saveButton.requestFocus();
				maintainQuestionsException.printStackTrace();
			}
		}

	}

	private ExamQuestionsVO generateExamQuestionsVO() {
		ExamQuestionsVO examQuestionsVO = new ExamQuestionsVO();
		examQuestionsVO.setSubjectName(subjectNameTextField.getText());
		examQuestionsVO.setModuleName(moduleNameTextField.getText());
		examQuestionsVO.setSubmoduleName(submoduleNameTextField.getText());
		examQuestionsVO.setQuestion(questionTextArea.getText());
		if (questionImagePathTextField.getText() != null
				&& questionImagePathTextField.getText().length() > 0) {
			examQuestionsVO
					.setQuestionImage(createInputStreamForImage(questionImagePathTextField
							.getText()));
		}
		examQuestionsVO.setQuestionYearMarkString(questionYearTextField
				.getText());
		examQuestionsVO.setAnswer(answerTextArea.getText());
		if (answerImagePathTextField.getText() != null
				&& answerImagePathTextField.getText().length() > 0) {
			examQuestionsVO
					.setAnswerImageStream(createInputStreamForImage(answerImagePathTextField
							.getText()));
		}
		return examQuestionsVO;
	}

	private InputStream createInputStreamForImage(String text) {
		FileInputStream fis = null;
		File file = new File(text);
	      try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fis;
	}

	private boolean isValidForSave() {
		boolean isValid = false;
		if (subjectNameTextField.getText() == null
				|| subjectNameTextField.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "Please specify the Subject",
					"Inane error", JOptionPane.ERROR_MESSAGE);
			subjectNameTextField.requestFocus();
			return isValid;
		}
		if (moduleNameTextField.getText() == null
				|| moduleNameTextField.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this,
					"Please specify the Module Name", "Inane error",
					JOptionPane.ERROR_MESSAGE);
			moduleNameTextField.requestFocus();
			return isValid;
		}
		if (submoduleNameTextField.getText() == null
				|| submoduleNameTextField.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this,
					"Please specify the Sub Module Name", "Inane error",
					JOptionPane.ERROR_MESSAGE);
			submoduleNameTextField.requestFocus();
			return isValid;
		}
		if (questionTextArea.getText() == null
				|| questionTextArea.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "Please specify the Question",
					"Inane error", JOptionPane.ERROR_MESSAGE);
			questionTextArea.requestFocus();
			return isValid;
		}
		if (questionYearTextField.getText() == null
				|| questionYearTextField.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this,
					"Please specify the Question year", "Inane error",
					JOptionPane.ERROR_MESSAGE);
			questionYearTextField.requestFocus();
			return isValid;
		} else {
			// TODO regex check
		}
		if (answerTextArea.getText() == null
				|| answerTextArea.getText().trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "Please specify the Answer",
					"Inane error", JOptionPane.ERROR_MESSAGE);
			answerTextArea.requestFocus();
			return isValid;
		}
		isValid = true;
		return isValid;
	}

	private void closeButtonActionPerformed(ActionEvent evt) {
		dispose();
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				new QuestionDetailsInterfaceUI().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify

	// End of variables declaration

}
